<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="utf-8"/>
    <title>java</title>
    <link rel="stylesheet" th:href="@{/css/myStyle.css}"/>
</head>
<body>
    <div class="n-head">
        <div class="g-doc f-cb">
            <div class="user">
                买家你好，<span class="name">buyer</span>！<a href="/logout">[退出]</a>
            </div>
            <ul class="nav">
                <li><a href="/">首页</a></li>
                <li><a href="/bill">账务</a></li>
                <li><a href="/preorder">购物车</a></li>
            </ul>
        </div>
    </div>
    <div class="g-doc" id="settleAccount">
        <div class="m-tab m-tab-fw m-tab-simple f-cb" >
            <h2>已添加到购物车的内容</h2>
        </div>
        <table id="newTable" class="m-table m-table-row n-table g-b3">

        </table>
        <div id="act-btn">
            <button class="u-btn u-btn-primary" id="back" onclick="back()">退出</button>
            <button class="u-btn u-btn-primary" id="Account" onclick="purchase()">购买</button>
        </div>
    </div>
    <div class="n-foot">
        <p>
            杭研有数：陈佳——在校作业
        </p>
    </div>
    <script>
        var arr;
        (function () {
            var table = document.getElementById("newTable");

            var hidediv = document.createElement("div");
            hidediv.innerHTML = "[[${record}]]";
            var data = hidediv.innerText;
            arr = JSON.parse(data);

            let str = "<tr>" +
                "<th>" + '内容名称'  + "</th>"+
                "<th>" + '数量' + "</th>" +
                "<th>" + '价格' + "</th>" +
                "</tr>";
            for(const i in arr){
                str = str +
                    "<tr>" +
                    "<td>" + arr[i].title  + "</td>"+
                    "<td>" +
                    "<span class=\"lessNum\" onclick='minusOne(this)'>"+ "-" + "</span>" +
                    "<span class=\"totalNum\" id=\"allNum\">" + arr[i].num + "</span>" +
                    "<span id=\"thisId\">" + arr[i].cid + "</span>" +
                    "<span class=\"moreNum\" onclick='addOne(this)'>"+ "+" + "</span>" + "</td>" +
                    "<td>" + arr[i].price + "</td>" +
                    "</tr>";
            }
            table.innerHTML = str;
        })();

        function addOne(obj) {
            console.log(obj.parentElement.children[1].textContent++);
            arr.filter(function (item) {
                return item.cid == obj.parentElement.children[2].textContent;
            })[0].num = obj.parentElement.children[1].textContent;

        }

        function minusOne(obj) {
            if(--obj.parentElement.children[1].textContent === 0){
                obj.parentElement.children[1].textContent++;
            }
            arr.filter(function (item) {
                return item.cid == obj.parentElement.children[2].textContent;
            })[0].num = obj.parentElement.children[1].textContent;
        }

        function back() {
            window.history.go(-1);
        }

        function purchase() {
            var loading = new Loading();
            var layer = new Layer();


            var newProducts = arr.map(function(arr){
                return {'cid':arr.cid,'number':arr.num};
            });
            if(newProducts.length === 0){
                alert("购物车中没有商品");
                return;
            }

            console.log(newProducts);
            layer.reset({
                content:'确认购买吗？',
                onconfirm:function(){
                    layer.hide();
                    loading.show();

                    var xhr = new XMLHttpRequest();
                    var data = JSON.stringify(newProducts);
                    xhr.onreadystatechange = function(){
                        if(xhr.readyState === 4){
                            var status = xhr.status;
                            if(status >= 200 && status < 300 || status === 304){
                                loading.result('购买成功',function(){location.href = "/";});
                            }else{
                                loading.result('购买失败');
                            }
                        }
                    };
                    xhr.open('post','/buy');
                    xhr.setRequestHeader('Content-Type','application/json');
                    xhr.send(data);
                }.bind(this)
            }).show();
        }

        //layer
        var Layer = function(){
            this.init();
        }
        Layer.prototype = {
            init:function(){
                this.isConfirmed = false;
                this.template ='<div class="m-winwrapper">\
							    <div class="winwrapper">\
							        <div class="m-win m-win-simple">\
							            <div class="winhd"><h2 class="wintt">{title}</h2></div>\
							            <div class="winbd">{content}</div>\
							            <div class="winft">\
							                <button type="button" class="u-btn u-btn-primary u-btn-fw" data-action="confirm">{confirmText}</button>\
							                <button type="button" class="u-btn u-btn-normal u-btn-fw" data-action="cancel">取消</button>\
							            </div>\
							        </div>\
							    </div>\
							</div>';
                this.body = document.createElement('div');
                this.body.style.display = 'none';
                document.body.appendChild(this.body);
                this.body.addEventListener('click',function(e){
                    var ele = e.target;
                    var action = ele.dataset && ele.dataset.action;
                    if(action == 'confirm'){
                        this.confirm();
                        return;
                    }
                    if(action == 'cancel'){
                        this.hide();
                        return;
                    }
                }.bind(this),false);
            },
            reset:function(options){
                var options = options || {};
                this.title = options.title || '提示';
                this.content = options.content || '';
                this.confirmText = options.confirmText || '确定';
                this.onconfirm = options.onconfirm || f;
                this.isConfirmed = false;
                return this;
            },
            confirm:function(){
                if(!this.isConfirmed){
                    this.onconfirm();
                }
                this.isConfirmed = true;
            },
            rend:function(){
                var html = this.template.replace('{title}',this.title).replace('{content}',this.content).replace('{confirmText}',this.confirmText);
                this.body.innerHTML = html;
            },
            show:function(){
                this.isConfirmed = false;
                this.rend();
                this.body.style.display = '';
            },
            hide:function(){
                this.isConfirmed = false;
                this.body.style.display = 'none';
            },
        };

        //loading
        var Loading = function(){
            this.init();
        }
        Loading.prototype = {
            init:function(){
                this.template ='<div class="v-load {class}"><div class="load"><i></i><b>{message}</b></div></div>';
                this.body = document.createElement('div');
                this.body.style.display = 'none';
                this.timer = null;
                document.body.appendChild(this.body);
            },
            rend:function(data){
                var html = data ? this.template.replace('{class}','v-load-result').replace('{message}',data.message) : this.template;
                this.body.innerHTML = html;
            },
            show:function(){
                this.rend();
                this.body.style.display = '';
            },
            result:function(message,callback){
                if(!message){
                    return;
                }
                this.rend({message:message});
                if(this.timer){
                    window.clearTimeout(this.timer);
                }
                this.timer = window.setTimeout(function(){
                    this.hide();
                    callback && callback();
                }.bind(this),1500);
            },
            hide:function(){
                this.body.style.display = 'none';
            }
        };

    </script>
</body>
</html>